<?php


namespace app\middleware;

use app\model\Plugin;
use app\model\Website;
use think\facade\App;
use think\facade\Cache;
use think\Request;

//PluginsMiddleware.php

class PluginsMiddleware
{
    protected $request;

    /**
     * 插件路由中间件
     *
     */
    public function handle(Request $request, \Closure $next)
    {
        $this->request = $request;
        //判断是否已安装，安装后才调用
        if (hcInstalled()) {
            $this->createRoutes();
        }
        return $next($request);
    }

    /**
     * 生成插件路由
     * @access protected
     * @return void
     */
    protected function createRoutes(): void
    {
        //获取当前网站列表和站点语言列表
        $domain = $this->request->host();
        $Website = new Website();
        $website = $Website->field('id,domain,seller_id,parent_id,status')->where(['domain'=>$domain])->find();
        if (!isset($website['id'])) {
            $siteId = 0;
        } else {
            $siteId = $website['id'];
        }
        $lang = setLang();

        // 加载路由
        $pluginsPath = App::getRootPath() . 'plugins';
        $routeDir = App::getRootPath() . "route";

        // 检查当前请求访问的域名是否已经生成了后台路由，没有生成下面的无需执行
        $file = $routeDir . '/' . $siteId . '_' . $lang . '_frontend.php';
        if (!file_exists($file)) {
            return;
        }

        $subDirs = hcScanDir("$pluginsPath/*", GLOB_ONLYDIR);

        $customerStr = [];
        if ($lang != config('lang')['default_lang']) {
            array_push($customerStr, "Route::group('$lang',function(){");
        } else {
            array_push($customerStr, 'Route::group(function(){');
        }

        $pluginModel = new Plugin();

        foreach ($subDirs as $subDir) {
            // 检查插件是否安装，安装才去更新路由
            $isInstall = $pluginModel->where('name', $subDir)->findOrEmpty();
            if (empty($isInstall) || $isInstall['status'] != 1) {
                continue;
            }

            $fileStr = [
                '<?php',
                'use think\facade\Route;',
                '',
            ];

            if ($siteId > 0 ) {
                $fileStr[] = "Route::domain('$domain',function(){";
            }


            $pluginRoutePath = $pluginsPath . DIRECTORY_SEPARATOR . $subDir . DIRECTORY_SEPARATOR . 'route' . DIRECTORY_SEPARATOR;
            if (is_dir($pluginRoutePath)) {
                $files = glob($pluginRoutePath . '*.php');
                foreach ($files as $file) {
                    $routePath = $routeDir . DIRECTORY_SEPARATOR . $siteId . '_' . $lang . "_plugin_{$subDir}.php";

                    // 缓存文件的MD5，判断是否修改，修改了才重新添加
                    $fileNameMd5 = md5_file($file);
                    if (Cache::get($file) == $fileNameMd5 && file_exists($routePath)) {
                        continue;
                    }
                    Cache::set($file, $fileNameMd5);

                    //当前插件文件的路由数据,生成真正的路由数据
                    $tempRoute = file($file);
                    foreach ($tempRoute as $key => $val) {
                        if (trim($val) == "<?php" || trim($val) == "use think\\facade\\Route;" || $val == PHP_EOL) {
                            unset($tempRoute[$key]);
                        }
                    }
                    $customerRoute = array_merge($customerStr, $tempRoute);
                    $customerRoute[] = "});";
                    $fileStr = array_merge($fileStr, $customerRoute);
                    if ($siteId > 0 ) {
                        array_push($fileStr, "});");
                    }
                    $content = join("\n", $fileStr);

                    $th = fopen($routePath, 'w');
                    file_put_contents($routePath, $content . "\n\n");
                    fclose($th);
                }
            }
        }
    }
}
